package pref.junx.flybird.network;

import pref.junx.flybird.base.model.ReturnModel;
import rx.Observer;

/**
 * RxJava操作结果二次封装
 *
 * 作者:李俊贤  on 16/7/25.
 * 邮箱:21194250@qq.com
 * 说明:
 */
public abstract class CustomObserver<T extends ReturnModel> implements Observer<T> {

    // 接口监听
    private OnFailedListener onFailedListener;

    public CustomObserver(OnFailedListener onFailedListener) {
        this.onFailedListener = onFailedListener;
    }

    @Override
    public void onNext(T returnBean) {
        // 若请求成功时错误码不为0, 则回调onFailed()
        if(returnBean.getErrorCode() != 0) onFailed(returnBean.getErrorCode());
        // 若请求成功且错误码为0, 则回调数据操作onResponse()
        else if(returnBean.getErrorCode() == 0) onSuccess(returnBean);
    }

    @Override
    public void onCompleted() {
        // TODO: 17/5/12
        // 无用, 舍弃, 空方法
    }

    protected void onFailed(int errorCode){
        if(null != onFailedListener) onFailedListener.onFailed(errorCode);
    }

    @Override
    public void onError(Throwable e) {
        if(null != onFailedListener) onFailedListener.onError(e);
    }

    public abstract void onSuccess(T returnBean);

}
